// 仪表盘功能实现

// 使用全局函数，不再使用ES模块导入

// 图表对象引用
let customerGrowthChart = null;
let salesDistributionChart = null;

// 初始化仪表盘
function initDashboard() {
    // 监听路由变更事件
    window.addEventListener('routeChanged', (e) => {
        if (e.detail.route === 'dashboard') {
            // 延迟一点时间初始化图表，确保DOM已经渲染
            setTimeout(() => {
                initCharts();
            }, 100);
        }
    });
    
    // 初始加载时，如果当前是仪表盘页面，则初始化图表
    if (document.getElementById('dashboard').classList.contains('active')) {
        setTimeout(() => {
            initCharts();
        }, 100);
    }
    
    // 初始化图表周期切换
    initChartPeriodToggle();
    
    // 添加数据刷新功能
    initDataRefresh();
}

// 初始化图表
function initCharts() {
    // 初始化客户增长趋势图表
    initCustomerGrowthChart();
    
    // 初始化销售业绩分布图表
    initSalesDistributionChart();
}

// 初始化客户增长趋势图表
function initCustomerGrowthChart() {
    const ctx = document.getElementById('customerGrowthChart');
    if (!ctx) return;
    
    // 如果图表已经存在，先销毁
    if (customerGrowthChart) {
        customerGrowthChart.destroy();
    }
    
    // 模拟数据 - 月度客户增长
    const months = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];
    const newCustomers = [45, 52, 49, 67, 78, 85, 79, 91, 105, 118, 125, 132];
    const totalCustomers = [320, 372, 421, 488, 566, 651, 730, 821, 926, 1044, 1169, 1289];
    
    customerGrowthChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: months,
            datasets: [
                {
                    label: '新增客户',
                    data: newCustomers,
                    borderColor: '#3498db',
                    backgroundColor: 'rgba(52, 152, 219, 0.1)',
                    borderWidth: 2,
                    tension: 0.4,
                    fill: true
                },
                {
                    label: '总客户数',
                    data: totalCustomers,
                    borderColor: '#2ecc71',
                    backgroundColor: 'transparent',
                    borderWidth: 2,
                    tension: 0.4,
                    fill: false
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'top',
                    labels: {
                        usePointStyle: true,
                        boxWidth: 6
                    }
                },
                tooltip: {
                    mode: 'index',
                    intersect: false,
                    backgroundColor: 'rgba(0, 0, 0, 0.8)',
                    titleColor: '#fff',
                    bodyColor: '#fff',
                    borderColor: '#3498db',
                    borderWidth: 1
                }
            },
            scales: {
                x: {
                    grid: {
                        display: false
                    }
                },
                y: {
                    beginAtZero: true,
                    grid: {
                        color: 'rgba(0, 0, 0, 0.05)'
                    }
                }
            },
            interaction: {
                intersect: false,
                mode: 'index'
            },
            animation: {
                duration: 1000,
                easing: 'easeOutQuart'
            }
        }
    });
}

// 初始化销售业绩分布图表
function initSalesDistributionChart() {
    const ctx = document.getElementById('salesDistributionChart');
    if (!ctx) return;
    
    // 如果图表已经存在，先销毁
    if (salesDistributionChart) {
        salesDistributionChart.destroy();
    }
    
    // 模拟数据 - 销售业绩分布
    const regions = ['华东', '华北', '华南', '西南', '西北', '东北'];
    const salesData = [350000, 280000, 220000, 180000, 150000, 109450];
    const colors = [
        'rgba(52, 152, 219, 0.8)',
        'rgba(155, 89, 182, 0.8)',
        'rgba(46, 204, 113, 0.8)',
        'rgba(231, 76, 60, 0.8)',
        'rgba(243, 156, 18, 0.8)',
        'rgba(26, 188, 156, 0.8)'
    ];
    
    salesDistributionChart = new Chart(ctx, {
        type: 'doughnut',
        data: {
            labels: regions,
            datasets: [{
                data: salesData,
                backgroundColor: colors,
                borderColor: '#fff',
                borderWidth: 2
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'right',
                    labels: {
                        padding: 20,
                        usePointStyle: true,
                        boxWidth: 6,
                        generateLabels: function(chart) {
                            const data = chart.data;
                            if (data.labels.length && data.datasets.length) {
                                const dataset = data.datasets[0];
                                const total = dataset.data.reduce((a, b) => a + b, 0);
                                
                                return data.labels.map((label, i) => {
                                    const value = dataset.data[i];
                                    const percentage = Math.round((value / total) * 100);
                                    return {
                                        text: `${label}: ${formatCurrency(value)} (${percentage}%)`,
                                        fillStyle: dataset.backgroundColor[i],
                                        strokeStyle: dataset.borderColor[i],
                                        lineWidth: dataset.borderWidth,
                                        hidden: false,
                                        index: i
                                    };
                                });
                            }
                            return [];
                        }
                    }
                },
                tooltip: {
                    backgroundColor: 'rgba(0, 0, 0, 0.8)',
                    titleColor: '#fff',
                    bodyColor: '#fff',
                    callbacks: {
                        label: function(context) {
                            const label = context.label || '';
                            const value = context.parsed;
                            const total = context.dataset.data.reduce((a, b) => a + b, 0);
                            const percentage = Math.round((value / total) * 100);
                            return `${label}: ${formatCurrency(value)} (${percentage}%)`;
                        }
                    }
                }
            },
            animation: {
                animateScale: true,
                animateRotate: true,
                duration: 1000,
                easing: 'easeOutQuart'
            },
            cutout: '60%'
        }
    });
}

// 初始化图表周期切换
function initChartPeriodToggle() {
    const periodBtns = document.querySelectorAll('.chart-period-btn');
    periodBtns.forEach(btn => {
        btn.addEventListener('click', () => {
            // 移除同一组按钮的活动状态
            const parent = btn.closest('.chart-period');
            parent.querySelectorAll('.chart-period-btn').forEach(b => {
                b.classList.remove('active');
            });
            
            // 添加当前按钮的活动状态
            btn.classList.add('active');
            
            // 根据图表类型和选择的周期更新数据
            const chartCard = btn.closest('.chart-card');
            if (chartCard) {
                if (chartCard.querySelector('#customerGrowthChart')) {
                    // 更新客户增长图表
                    updateCustomerGrowthChart(btn.textContent.trim());
                } else if (chartCard.querySelector('#salesDistributionChart')) {
                    // 更新销售分布图表
                    updateSalesDistributionChart(btn.textContent.trim());
                }
            }
        });
    });
}

// 更新客户增长图表
function updateCustomerGrowthChart(period) {
    if (!customerGrowthChart) return;
    
    let labels, newCustomers, totalCustomers;
    
    switch (period) {
        case '季度':
            labels = ['Q1', 'Q2', 'Q3', 'Q4'];
            newCustomers = [146, 230, 275, 375];
            totalCustomers = [320, 550, 825, 1289];
            break;
        case '年度':
            labels = ['2020', '2021', '2022', '2023', '2024'];
            newCustomers = [280, 365, 420, 510, 1289];
            totalCustomers = [380, 745, 1165, 1675, 2964];
            break;
        default: // 月度
            labels = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];
            newCustomers = [45, 52, 49, 67, 78, 85, 79, 91, 105, 118, 125, 132];
            totalCustomers = [320, 372, 421, 488, 566, 651, 730, 821, 926, 1044, 1169, 1289];
    }
    
    // 更新图表数据
    customerGrowthChart.data.labels = labels;
    customerGrowthChart.data.datasets[0].data = newCustomers;
    customerGrowthChart.data.datasets[1].data = totalCustomers;
    customerGrowthChart.update('active');
}

// 更新销售分布图表
function updateSalesDistributionChart(period) {
    if (!salesDistributionChart) return;
    
    let salesData;
    
    switch (period) {
        case '上月':
            salesData = [320000, 260000, 190000, 160000, 130000, 95000];
            break;
        case '全年':
            salesData = [4200000, 3360000, 2640000, 2160000, 1800000, 1313400];
            break;
        default: // 本月
            salesData = [350000, 280000, 220000, 180000, 150000, 109450];
    }
    
    // 更新图表数据
    salesDistributionChart.data.datasets[0].data = salesData;
    salesDistributionChart.update('active');
}

// 初始化数据刷新功能
function initDataRefresh() {
    // 每30秒随机更新统计数据，模拟实时数据更新
    setInterval(() => {
        if (document.getElementById('dashboard').classList.contains('active')) {
            updateRandomStats();
        }
    }, 30000);
}

// 更新随机统计数据
function updateRandomStats() {
    const statValues = document.querySelectorAll('.stat-value');
    const statChanges = document.querySelectorAll('.stat-change');
    
    statValues.forEach((valueElement, index) => {
        let currentValue = valueElement.textContent;
        
        // 处理不同类型的数值
        if (currentValue.startsWith('¥')) {
            // 货币类型
            const numValue = parseFloat(currentValue.replace(/[^\d.]/g, ''));
            const change = numValue * (Math.random() * 0.01 - 0.005); // -0.5% to +0.5%
            const newValue = numValue + change;
            valueElement.textContent = formatCurrency(newValue);
            
            updateChangeIndicator(statChanges[index], change, numValue);
        } else if (currentValue.includes('%')) {
            // 百分比类型
            const numValue = parseFloat(currentValue);
            const change = (Math.random() * 0.4 - 0.2); // -0.2% to +0.2%
            const newValue = Math.max(0, Math.min(100, numValue + change)); // 确保在0-100范围内
            valueElement.textContent = newValue.toFixed(1) + '%';
            
            updateChangeIndicator(statChanges[index], change, 100); // 使用100作为基数
        } else {
            // 普通数字类型
            const numValue = parseInt(currentValue.replace(/[^\d]/g, ''));
            const change = Math.floor(numValue * (Math.random() * 0.005 - 0.0025)); // -0.25% to +0.25%
            const newValue = Math.max(0, numValue + change);
            valueElement.textContent = newValue.toLocaleString();
            
            updateChangeIndicator(statChanges[index], change, numValue);
        }
    });
}

// 更新变化指示器
function updateChangeIndicator(element, change, baseValue) {
    if (!element) return;
    
    const percentage = Math.abs((change / baseValue) * 100);
    const sign = change >= 0 ? '+' : '';
    
    element.textContent = sign + percentage.toFixed(1) + '%';
    element.className = change >= 0 ? 'stat-change positive' : 'stat-change negative';
}

// 页面加载完成后初始化
window.addEventListener('DOMContentLoaded', initDashboard);